package com.gitee.kamismile.stoneEureka.client.handler;

import com.gitee.kamismile.gatewayAgent.client.handler.ClientHeartBeatHandler;
import com.gitee.kamismile.gatewayAgent.client.handler.GateWayClientInitializer;
import com.gitee.kamismile.gatewayAgent.protobuf.Message;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import io.netty.handler.timeout.IdleStateHandler;
import com.gitee.kamismile.stoneEureka.client.EurekaClientConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class EurekaClientInitializer extends GateWayClientInitializer {

    @Autowired
    private EurekaClientConstant eurekaClientConstant;
    @Autowired
    private EureKaClientGateWayClientHelper eureKaClientGateWayClientHelper;
    @Autowired
    private ApplicationContext applicationContext;

    @Override
    public void initChannel(SocketChannel ch) {
        ChannelPipeline p = ch.pipeline();
        p.addLast(new ChannelHandler[]{new ProtobufVarint32FrameDecoder()});
        p.addLast(new ChannelHandler[]{new ProtobufDecoder(Message.RouterMessage.getDefaultInstance())});
        p.addLast(new ChannelHandler[]{new ProtobufVarint32LengthFieldPrepender()});
        p.addLast(new ChannelHandler[]{new ProtobufEncoder()});
        p.addLast(new ChannelHandler[]{new IdleStateHandler(0L, 0L, 100L, TimeUnit.SECONDS)});
        p.addLast(new ChannelHandler[]{new ClientHeartBeatHandler()});
        EureKaClientHandler eureKaClientHandler = new EureKaClientHandler();
        eureKaClientHandler.setEurekaClientConstant(eurekaClientConstant);
        eureKaClientHandler.setApplicationContext(applicationContext);
        eureKaClientHandler.setEureKaClientGateWayClientHelper(eureKaClientGateWayClientHelper);
        p.addLast(new ChannelHandler[]{eureKaClientHandler});

    }
}
